﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace Pcubed.Shuie
{
  class XmlValidator
  {
    public Boolean Failed { get; private set; }
    public String Error { get; set; }

    public Boolean ValidateXml(String xmlFilename)
    {
      XmlReaderSettings settings = new XmlReaderSettings { ValidationType = ValidationType.Schema };

      XmlSchemaSet schemas = new XmlSchemaSet();
      XmlReader xsdReader = XmlReader.Create(
        new MemoryStream(UTF8Encoding.Default.GetBytes(Properties.Resources.shuie_entry))
      );
      schemas.Add(null, xsdReader);
      settings.Schemas = schemas;

      settings.ValidationEventHandler += ValidationEventHandler;
      XmlReader validator = XmlReader.Create(xmlFilename, settings);
      Failed = false;

      try
      {
        while (validator.Read()) { }
      }
      catch (XmlException err)
      {
        Failed = true;
        Error = err.Message;
      }
      finally
      {
        validator.Close();
      }

      return !Failed;
    }

    private void ValidationEventHandler(object sender, ValidationEventArgs args)
    {
      Failed = true;
      Error = args.Message;
    }
  }
}
